//ShaTest file

#include<iostream>
#include<string>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#include <ctime>
#include <openssl/sha.h>
#include <sha1.h>
using namespace std;

unsigned char *GetSHA1(const char *filename)
{	   
	  
       unsigned char* results = (unsigned char*)malloc(20);
       struct stat st;
       SHA_CTX sha;
	   SHA1_Init(&sha);
       FILE *fp = fopen(filename,"r");
       stat(filename,&st);
       if(fp==NULL){
               cerr<<"File can not be opened; the program will terminate now."<<endl;
               exit(1);
       }
       
	   unsigned int fsize = st.st_size;
	   unsigned int count = fsize/8192;

	   cout<<st.st_size<<endl;
	   //exit(1);

	   unsigned int actsize = fsize;

	   if(count>=1 && (fsize%8192)!=0){
		   count=count+1;
	   }else{
		   if(count==0){
			   count=1;
		   }else{
			   count=fsize/8192;
		   }
	   }

	   unsigned int buf_count =0;
	   for(unsigned int icount=0;icount<count;icount++){

		   if(actsize>=8192){
			   buf_count=8192;
		   }else{
			   buf_count=actsize;
		   }
		   actsize = actsize - 8192;

	   unsigned char* MsgBuf = (unsigned char*)malloc(8192);
	   memset(MsgBuf,0,8192);

	   size_t bytes_read;

	   bytes_read = fread(MsgBuf,1,buf_count,fp);
	   cout<<bytes_read<<endl;

	   SHA1_Update(&sha,MsgBuf,buf_count);
        
       buf_count=0;
	   free(MsgBuf);
	   }//count for loop
	   
      
       SHA1_Final(results,&sha);
       fclose(fp);
       for(int i=0;i<20;i++)
       {
               printf("%02x",results[i]);
       }
       cout<<endl;

     return results;

}
int main()
{
	   unsigned char* mySha = new unsigned char[20];
       memcpy(mySha,GetSHA1("sv_node.cpp"),20);

       cout<<"mySha"<<endl;
	    for(int i=0;i<20;i++)
       {
               printf("%02x",mySha[i]);
       }
       cout<<endl;

       return 0;
}